<?php
namespace User\Controller;

use Common\Controller\AdminbaseController;

class AmountController extends AdminbaseController {
    private $banks;
    public function __construct() {
        parent::__construct();
        $this->model=M("amount",'system_',C('DB_CONFIG2'));
        $this->banks=array(
            '中国银行'=>'0104',
            '中国农业银行'=>'0103',
            '中国工商银行'=>'0102',
            '中国建设银行'=>'0105',
            '招商银行'=>'0308',
            '交通银行'=>'0301',
            '兴业银行'=>'0309',
            '中国民生银行'=>'0305',
            '平安银行股份有限公司'=>'0307',
            '中国邮政储蓄银行股份有限公司'=>'0403',
            '中国光大银行'=>'0303',
            '中信银行'=>'0302',
            '华夏银行'=>'0304',
            '广东发展银行'=>'0306',
            '上海浦东发展银行'=>'0310',
        );
    }
    public function index(){
        $where=array();
        $request=I('request.');
        if(!empty($request['amount'])){
            $where['amount']  = $request['amount'];
        }
        if($request['status']!=''){
            $where['status']  = array('eq', $request['status']?'1':'0');
        }
    	$count=$this->model->where($where)->count();
    	$page = $this->page($count, 20);
    	
    	$list = $this->model
    	->where($where)
    	->order("amount DESC,id asc")
    	->limit($page->firstRow . ',' . $page->listRows)
    	->select();
    	$this->assign('list', $list);
    	$this->assign("page", $page->show('Admin'));

    	$this->display();
    }

    public function info(){
        $id= I('get.id',0,'intval');
        if (!empty($id)) {
            $result =$this->model->where(array("id"=>$id))
                ->find();
            $this->assign('info', $result);
            $this->assign('list_title', '编辑额度');
        } else {
            $this->assign('list_title', '添加额度');
        }
        $this->display();
    }
    public function info_save(){
        $data= I('post.options');
        if(empty($data)){
            $this->error('请刷新重试！');
        }
        $data['uptime']=date('Y-m-d H:i:s');
        if(!empty($data['id'])){
            $this->model->where(array('id'=>$data['id']))->save($data);
            $this->success("额度编辑成功！", U("Amount/index"));
        }else{
            $this->model->add($data);
            $this->success("额度添加成功！", U("Amount/index"));
        }
    }
    /*
     * 代付
     */
    public function bank_daifu(){
        $amount=I('post.amount',0);
        if(!empty($amount)){
            $stutus=true;
            if($stutus) $url='https://fht.fuiou.com/req.do'; else $url='https://fht-test.fuiou.com/fuMer/req.do';
            $data=array(
                'bankno'=>'0308',//总行代码
                'cityno'=>'5810',//城市代码
                'branchnm'=>'招商银行股份有限公司广州丰兴支行',//支行名称
                'accntno'=>'6214831201586762',//卡号
                'accntnm'=>'上官志勇',//名称
                'amt'=>$amount*100,
                'mobile'=>'13602882656',
                //'orderno'=>date('Ymd').substr(microtime(true) . rand(1, 10000), -5),
            );
            $insert=array(
                'amount'=>$amount,
                'accntno'=>$data['accntno'],
                'accntnm'=>$data['accntnm'],
                'id'=>date('Ymd').substr(microtime(true) . rand(1, 10000), -5),
            );
            M('orders')->add($insert);
            $data['orderno']=$insert['id'];
            $fm='<?xml version="1.0" encoding="utf-8" standalone="yes"?><payforreq> <ver>1.00</ver> <merdt>'.date('Ymd').'</merdt> <orderno>'.$data['orderno'].'</orderno> <bankno>'.$data['bankno'].'</bankno> <cityno>'.$data['cityno'].'</cityno> <branchnm>'.$data['branchnm'].'</branchnm> <accntno>'.$data['accntno'].'</accntno> <accntnm>'.$data['accntnm'].'</accntnm> <amt>'.$data['amt'].'</amt> <mobile>'.$data['mobile'].'</mobile> </payforreq >';
            $key='qetxvpmm58g5o77ywgqu371298p93bwz';
            $post_data=array(
                'merid'=>'0005810F0467776',
                'reqtype'=>'payforreq',
                'xml'=>$fm,
            );
            $post_data['mac']=md5($post_data['merid'].'|'.$key.'|'.$post_data['reqtype'].'|'.$post_data['xml']);
            $data=$this->http_post($url,$post_data);
            libxml_disable_entity_loader(true);
            $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
            if((string)$data->ret=='0000'){
                $up=array('ret'=>(string)$data->ret);
            }else{
                $up=array('ret'=>(string)$data->memo);
            }
            M('orders')->where(array('id'=>$insert['id']))->save($up);
            $this->success("提交成功！", U("Amount/bank_daifu"));
        }else{
            $count=M('orders')->count();
            $page = $this->page($count, 20);
            $list=M('orders')
                ->order("crtime DESC")
                ->limit($page->firstRow . ',' . $page->listRows)
                ->select();
            $this->assign('list', $list);
            $this->assign("page", $page->show('Admin'));
            $this->display();
        }
    }
    /*
     * 代付 开通数字 1诺诺信 2助发 3悦花花
     */
    public function daifu(){
        $type=1;
        $oid=I('get.id',0);
        if(empty($oid)){
            $this->error( '请刷新重试!' );
        }
        $order=M( "ders a", 'or', C( 'DB_CONFIG2' ))
            ->field('a.id,a.user_id,a.amount,a.interest,a.examine,a.consulting,a.status,b.name,b.bank,b.silver_card')
            ->join('LEFT JOIN system_user b on a.user_id=b.id')->where(['a.id'=>$oid])->find();
        if(empty($order['id']) || empty($order['user_id'])){
            $this->error( '该借款不存在!' );
        }
        if($order['status']!=8){
            $this->error( '只有放款成功的客户才能提交放款申请!' );
        }
        if(empty($order['silver_card']) || empty($order['bank'])){
            $this->error( '该客户未绑定银行卡!' );
        }
        if(empty($this->banks[$order['bank']])){
            $this->error( '该客户银行卡只能手工转账!' );
        }
        $pay=M( "pay", 'order_', C( 'DB_CONFIG2' ) )->where(['user_id'=>$order['user_id'],'oid'=>$oid])->find();
        if(!empty($pay)){
            $this->error( '该借款已申请,请勿重复操作!' );
        }
        $url='https://fht.fuiou.com/req.do';;
        $data=array(
            'bankno'=>$this->banks[$order['bank']],//总行代码
            'cityno'=>'1000',//城市代码
            'accntno'=>$order['silver_card'],//卡号
            'accntnm'=>$order['name'],//名称
            'amt'=>($order['amount']-$order['interest']-$order['examine']-$order['consulting']-10)*100,
        );
        if($data['amt']<=0){
            $this->error( '借款有误,请重新检查!' );
        }
        $insert=array(
            'oid'=>$order['id'],
            'user_id'=>$order['user_id'],
            'examine_id'=>get_current_admin_id(),
            'crtime'=>date('Y-m-d H:i:s'),
            'bank'=>$order['bank'],
            'amount'=>$data['amt'],
            'accntno'=>$data['accntno'],
            'id'=>$type.date('Ymd').substr(microtime(true) . rand(1, 10000), -5),
        );
        M( "pay", 'order_', C( 'DB_CONFIG2' ) )->add($insert);
        $data['orderno']=$insert['id'];
        $fm='<?xml version="1.0" encoding="utf-8" standalone="yes"?><payforreq> <ver>1.00</ver> <merdt>'.date('Ymd').'</merdt> <orderno>'.$data['orderno'].'</orderno> <bankno>'.$data['bankno'].'</bankno> <cityno>'.$data['cityno'].'</cityno> <accntno>'.$data['accntno'].'</accntno> <accntnm>'.$data['accntnm'].'</accntnm> <amt>'.$data['amt'].'</amt> </payforreq >';
        $key='';
        if(empty($key)){
            $this->error( '代付暂时未开放!' );
        }
        $post_data=array(
            'merid'=>'0005810F0467776',
            'reqtype'=>'payforreq',
            'xml'=>$fm,
        );
        $post_data['mac']=md5($post_data['merid'].'|'.$key.'|'.$post_data['reqtype'].'|'.$post_data['xml']);
        $data=$this->http_post($url,$post_data);
        libxml_disable_entity_loader(true);
        $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $up=array('ret'=>(string)$data->memo);
        M( "pay", 'order_', C( 'DB_CONFIG2' ) )->where(['user_id'=>$order['user_id'],'oid'=>$oid])->save($up);
        //$this->success("提交成功！", U("Amount/bank_daifu"));
        $this->success("提交成功！", U("examine/cntinued_loan"));
    }
    /*
     * 订单查询
     */
    public function check_order(){
       // $id=I('get.id',0);
//        if(empty($id)){
//            $this->error('请刷新重试！');
//        }
        $stutus=true;
        if($stutus) $url='https://fht.fuiou.com/req.do'; else $url='https://fht-test.fuiou.com/fuMer/req.do';
        $dt=[
            'start'=>date('Ymd',strtotime('-13days')),
            'end'=>date('Ymd'),
        ];
        $fm='<?xml version="1.0" encoding="utf-8" standalone="yes"?> <qrytransreq> <ver>1.00</ver> <busicd>AP01</busicd>  <startdt>'.$dt['start'].'</startdt> <enddt>'.$dt['end'].'</enddt>  </qrytransreq>';
        $key='';
        if(empty($key)){
            $this->error( '查询暂时未开放!' );
        }
        $post_data=array(
            'merid'=>'0005810F0467776',
            'reqtype'=>'qrytransreq',
            'xml'=>$fm,
        );
        $post_data['mac']=md5($post_data['merid'].'|'.$key.'|'.$post_data['reqtype'].'|'.$post_data['xml']);
        $data=$this->http_post($url,$post_data);
        $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        if((string)$data->ret=='0000'){
            $data = json_decode(json_encode($data),true);
            $sql=[];
            $i=0;
            foreach($data['trans'] as $v){
                $sql[$i][]='WHEN "'.$v['orderno'].'" THEN "'.$v['state'].'"';
                if(count($sql[$i])==50){
                    $i+=1;
                }
            }
            foreach($sql as $v){
                $sqls='UPDATE order_pay SET state = CASE oid '.implode(' ',$v).' end';
                M("pay",'orders_',C('DB_CONFIG2'))->query($sqls);
            }
            //$this->success("提交成功！", U("Amount/bank_daifu"));
            $this->success("查询成功！", U("examine/cntinued_loan"));
        }else{
            $this->error($data->memo);
        }
    }
    function http_post($url,$param,$headers=null,$post_file=false){
        $oCurl = curl_init();
        curl_setopt ( $oCurl, CURLOPT_SAFE_UPLOAD, false);
        if(preg_match('/^https/', $url)){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if(is_string($param) || $post_file){
            $strPOST = $param;
        }else{
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        if($headers){
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            //$sContent=json_decode($sContent,true);
            return $sContent;
        }else{
            return false;
        }
    }
}
